package com.ruoyi.web.controller.bargain;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.VelocityContext;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.jiugongge.domain.Jiugongge;
import com.ruoyi.jiugongge.domain.JiugonggePrizes;
import com.ruoyi.jiugongge.domain.JiugonggeRecord;
import com.ruoyi.jiugongge.domain.JiugonggeRegistration;
import com.ruoyi.jiugongge.domain.WeixinDto;
import com.ruoyi.jiugongge.mapper.JiugonggePrizesMapper;
import com.ruoyi.jiugongge.mapper.JiugonggeRegistrationMapper;
import com.ruoyi.jiugongge.service.IJiugonggePrizesService;
import com.ruoyi.jiugongge.service.IJiugonggeRecordService;
import com.ruoyi.jiugongge.service.IJiugonggeService;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.bargain.domain.Bargain;
import com.ruoyi.bargain.domain.BargainRecord;
import com.ruoyi.bargain.domain.BargainRegistration;
import com.ruoyi.bargain.service.IBargainRecordService;
import com.ruoyi.bargain.service.IBargainRegistrationService;
import com.ruoyi.bargain.service.IBargainService;
import com.ruoyi.common.utils.AjaxJson;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LotteryUtil;
import com.ruoyi.common.utils.RandomUtils;
import com.ruoyi.common.utils.StringUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDUtil;
import com.ruoyi.common.utils.WeiXinHttpUtil;

/**
 * 砍价活动 信息操作处理
 * 
 * @author lzy
 * @date 2019-03-07
 */
@Controller
@RequestMapping("/bargain")
public class BargainIndexController extends BaseController {

   @Autowired
   private IBargainService bargainService;
   @Autowired
   private IBargainRegistrationService bargainRegistrationService;
   @Autowired
   private IBargainRecordService bargainRecordService;

	protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(BargainIndexController.class);



	 /**
	 * @功能   跳转活动首页  
	 * @时间 2019年3月7日 
	 */
	@RequestMapping(value = "/toIndex",method ={RequestMethod.GET, RequestMethod.POST})
	 public String toIndex(@ModelAttribute WeixinDto weixinDto,HttpServletRequest request,HttpServletResponse response,ModelMap model) throws Exception{
		 logger.info("-----------------砍价跳转首页活动开始------------------------");
		 
		 //装载微信所需参数
		 String jwid = weixinDto.getJwid();
		 String appid = weixinDto.getAppid();
		 String actId = weixinDto.getActId();
		 String openid = weixinDto.getOpenid();

		 logger.info("-----------------未解码时跳转活动用户昵称------------------------"+weixinDto.getNickname());
		 
        String nickname = URLDecoder.decode(weixinDto.getNickname(), "UTF-8");
        weixinDto.setNickname(nickname);
        
         /*weixinDto.setNickname("lzy6666"); 
		 String nickname = weixinDto.getNickname();
		 weixinDto.setHeadimgurl("https://micromart.oss-cn-beijing.aliyuncs.com/timg.jpg");*/
        
        logger.info("-----------------解码后跳转活动用户昵称------------------------"+nickname);
		
		//转换粉丝信息 （用户昵称、头像、关注状态）
		//setWeixinDto(weixinDto);
		 
		 String viewName = null;
		 try {
			//获取活动信息
			 Bargain gzWxActBargain = bargainService.selectBargainById(weixinDto.getActId());
			 
			 if(gzWxActBargain==null){
				 model.addAttribute("errCode",false);
				 model.addAttribute("errMsg", "活动不存在");
				 return "bargain/error";
			 }
			 
			 model.addAttribute("bargain", gzWxActBargain);
			
			 // 参数验证
			String validateWeixinDtoParam = validateWeixinDtoParam(weixinDto);

				if (validateWeixinDtoParam.equals("success") == false) {
				    model.addAttribute("errCode",false);
					model.addAttribute("errMsg", validateWeixinDtoParam);					
					return "bargain/error";
				}
			

		
			 if(!weixinDto.getJwid().equals(gzWxActBargain.getJwid())){
				 model.addAttribute("errCode",false);
				 model.addAttribute("errMsg", "活动不属于该微信公众号");
				 return "bargain/error";
			 }
			
			 //有效期内可参与  
			 Date currDate = new Date();
			 /*if(currDate.before(gzWxActBargain.getBegainTime())){
				  String begainTime = DateUtil.convertToShowTime(gzWxActBargain.getBegainTime());
				  model.addAttribute("errCode",false);
				  model.addAttribute("errMsg", "活动未开始,开始时间为"+begainTime+",请耐心等待！");
				  return "bargain/error";
				 
			 }*/
			 if(currDate.after(gzWxActBargain.getEndTime())){
				 model.addAttribute("actStatus", "0");//活动结束
				 
			 }else{
				 model.addAttribute("actStatus", "1");
			 }
			
			 List<BargainRecord> bargainRecordList = new ArrayList<BargainRecord>();
			 if(StringUtil.isEmpty(gzWxActBargain.getTemplate())){
				 gzWxActBargain.setTemplate("co");
			 }
			 //判断是否是分享活动
			 if(isShareAct(weixinDto)){
				 if(weixinDto.getFxOpenid().equals(openid)){
					 viewName = "bargain/bargain";
				 }else{
					 viewName = "bargain/fxbargain";
				 }
				 
				//根据分享人openid查询分享人的报名信息
				 BargainRegistration gzWxActBargainRegistration =  bargainRegistrationService.queryRegistrationByOpenidAndActId(weixinDto.getFxOpenid(), weixinDto.getActId());
				 if(gzWxActBargainRegistration==null){
					 model.addAttribute("errCode",false);
					 model.addAttribute("errMsg", "活动无效");
					 return "bargain/error";
				 }
				 model.addAttribute("bargainRegistration", gzWxActBargainRegistration);
				 //查询砍价记录
				 bargainRecordList =  bargainRecordService.queryBargainRecordListByRegistrationId(gzWxActBargainRegistration.getId());
			 }else{
				 viewName = "bargain/bargain";
				 /*if("0".equals(weixinDto.getSubscribe())){
					 throw new GzbargainException(GzbargainExceptionEnum.ACT_BARGAIN_NO_FOCUS,"非关注用户");
				 }*/
				 weixinDto.setFxOpenid(openid);
				 //根据访问人openid查询访问人的报名信息 
				 BargainRegistration gzWxActBargainRegistration =  bargainRegistrationService.queryRegistrationByOpenidAndActId(openid, weixinDto.getActId());
				 if(gzWxActBargainRegistration==null){
					 gzWxActBargainRegistration = new BargainRegistration();
					 gzWxActBargainRegistration.setId(RandomUtils.generateID());
					 gzWxActBargainRegistration.setActId(weixinDto.getActId());
					 gzWxActBargainRegistration.setOpenid(openid);
					 gzWxActBargainRegistration.setNickname(nickname);
					 gzWxActBargainRegistration.setProductName(gzWxActBargain.getProductName());
					 gzWxActBargainRegistration.setProductNewPrice(gzWxActBargain.getProductPrice());
					 gzWxActBargainRegistration.setProductPrice(gzWxActBargain.getProductPrice());
					 gzWxActBargainRegistration.setCreateTime(new Date());
					 gzWxActBargainRegistration.setJwid(gzWxActBargain.getJwid());
					 bargainRegistrationService.insertBargainRegistration(gzWxActBargainRegistration);
				 }else{
					//查询砍价记录
					bargainRecordList =  bargainRecordService.queryBargainRecordListByRegistrationId(gzWxActBargainRegistration.getId());
				 }
				 model.addAttribute("bargainRegistration", gzWxActBargainRegistration);
			 }
			 
			 model.addAttribute("recordListCount", bargainRecordList==null?0:bargainRecordList.size());
			 model.addAttribute("recordList", bargainRecordList);
			 model.addAttribute("weixinDto", weixinDto);
			 
			 
			//微信分享参数------------------
			 model.addAttribute("nonceStr", WeiXinHttpUtil.nonceStr);
			 model.addAttribute("timestamp", WeiXinHttpUtil.timestamp);

			 model.addAttribute("hdUrl",gzWxActBargain.getHdurl());
			 model.addAttribute("appId", appid);
			 model.addAttribute("signature",WeiXinHttpUtil.getRedisSignature(request, jwid));
			 
		

		} catch (Exception e) {
			 logger.info("-------------出错了--------------"+e.getMessage());
		}
		return viewName; 
	 }
	
	
	
	/**
	 * @功能    砍价 
	 * @时间 2019年3月9日 
	 */
	@RequestMapping(value = "/gobargain",method ={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public AjaxJson bargain(@ModelAttribute BargainRecord gzWxActBargainRecord,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		logger.info("------------------砍价活动开始----------------------------");
		try {
			//参数验证
			validateBargainRecordParam(gzWxActBargainRecord);
						
			BargainRegistration bargainRegistration = bargainRegistrationService.selectBargainRegistrationById(gzWxActBargainRecord.getRegistrationId());
			
			// 判断是否已经领奖了
			Map<String, Object> dataMap = new HashMap<String, Object>();
			if ("1".equals(bargainRegistration.getAwardsStatus())) {
				dataMap.put("cutStatus", "received");
				j.setAttributes(dataMap);
				j.setSuccess(false);
				return j;
			}
			
			//判断是否已经砍价
			List<BargainRecord> bargainRecordList = bargainRecordService.queryBargainRecordListByRegistrationIdAndOpenid(gzWxActBargainRecord.getRegistrationId(), gzWxActBargainRecord.getOpenid());
			if(bargainRecordList!=null&&bargainRecordList.size()>0){
				dataMap.put("cutStatus", "bargained");
				j.setAttributes(dataMap);
				return j;
			}
			String cutCount = bargainRecordService.bargain(bargainRegistration,gzWxActBargainRecord);
			dataMap.put("cutStatus", cutCount);
			dataMap.put("cutPrice", gzWxActBargainRecord.getCutPrice());
			j.setSuccess(true);
			j.setAttributes(dataMap);
		}catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("砍价失败!");
			logger.error("bargain error:{}", e.getMessage());
		}
		return j;
	}
	
	
	
	private void validateBargainRecordParam(BargainRecord gzWxActBargainRecord){
		 if(StringUtils.isEmpty(gzWxActBargainRecord.getRegistrationId())){
			 try {
				throw new Exception("报名ID不能为空");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 if(StringUtils.isEmpty(gzWxActBargainRecord.getOpenid())){
			 try {
				throw new Exception("砍价人openid不能为空");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }

	 }
	
	
	

	private String validateWeixinDtoParam(WeixinDto weixinDto) {
		if (StringUtils.isEmpty(weixinDto.getActId())) {

			return "活动ID不能为空";
		}
		if (StringUtils.isEmpty(weixinDto.getOpenid())) {

			return "参与人openid不能为空";
		}
		if (StringUtils.isEmpty(weixinDto.getJwid())) {
	
			return "微信ID不能为空";
		}
		return "success";
	}


	/**
	 * 微信获取个人信息util
	 * 
	 * @param weixinDto
	 * @return 获取头像 Map两个键headimgurl,fxheadimgurl
	 */
	private Map<String, String> setWeixinDto(WeixinDto weixinDto) {
		logger.info("setWeixinDto parameter weixinDto={}", new Object[] { weixinDto });
		Map<String, String> map = new HashMap<String, String>();
		try {
			if (weixinDto.getOpenid() != null) {
				JSONObject jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getOpenid(), weixinDto.getJwid());
				logger.info("setWeixinDto Openid getGzUserInfo jsonObj={}", new Object[] { jsonObj });
				if (jsonObj != null && jsonObj.containsKey("subscribe")) {
					weixinDto.setSubscribe(jsonObj.getString("subscribe"));
				} else {
					weixinDto.setSubscribe("0");
				}
				if (jsonObj != null && jsonObj.containsKey("nickname")) {
					weixinDto.setNickname(jsonObj.getString("nickname"));
				} else {
					weixinDto.setNickname("");
				}
				if (jsonObj != null && jsonObj.containsKey("headimgurl")) {
					map.put("headimgurl", jsonObj.getString("headimgurl"));
				} else {
					map.put("fxheadimgurl", "");
				}
			}
			if (StringUtils.isNotEmpty(weixinDto.getFxOpenid())) {
				JSONObject jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getFxOpenid(), weixinDto.getJwid());
				logger.info("setWeixinDto FxOpenid getGzUserInfo jsonObj={}", new Object[] { jsonObj });
				if (jsonObj != null && jsonObj.containsKey("nickname")) {
					weixinDto.setFxNickname(jsonObj.getString("nickname"));
				} else {
					weixinDto.setFxNickname("");
				}
				if (jsonObj != null && jsonObj.containsKey("headimgurl")) {
					map.put("fxheadimgurl", jsonObj.getString("headimgurl"));
				} else {
					map.put("fxheadimgurl", "");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("setWeixinDto e={}", new Object[] { e });
		}
		return map;
	}

	/**
	 * @功能：随机生成兑奖码
	 * @return
	 */
	private synchronized static String getCoupon() {
		char ch[] = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
				'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
				'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 20; i++) {
			sb.append(ch[rand.nextInt(62)]);
		}
		return sb.toString();
	}
	
	
	 private boolean isShareAct(WeixinDto weixinDto){
		 boolean flag = false;
		 if(StringUtils.isNotEmpty(weixinDto.getFxOpenid())){
			 flag = true;
		 }
		 return flag;
	 }

}
